package cn.workreport.util;

import cn.workreport.config.conf.TokenConfiguration;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public  class TokenUtil {

//    @Value("${token.privateKey}")
//    private String privateKey;

    @Autowired
    TokenConfiguration tokenConfiguration;

    /**
     * 生成加密 token
     */
    public String getToken(Integer userId) {
        // 这个是放到负载payLoad 里面,魔法值可以使用常量类进行封装.
        String token = JWT
                .create()
                .withClaim("userId", Long.valueOf(userId))
                .withClaim("timeStamp", System.currentTimeMillis())
                .sign(Algorithm.HMAC256(tokenConfiguration.getPrivateKey()));
        System.out.println("\t生成的 token ==>" + token);
        return token;
    }


    /**
     * 解析 token
     * (优化可以用常量固定魔法值+使用DTO在 mvc 之前传输数据，而不是 map)
     * {
     * "userId": "3412435312",
     * "timeStamp": "134143214"
     * }
     */
    public Map<String, Long> parseToken(String token) {
        HashMap<String, Long> map = new HashMap<>();
        DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(tokenConfiguration.getPrivateKey())).build().verify(token);
        Claim userId = decodedJWT.getClaim("userId");
        Claim timeStamp = decodedJWT.getClaim("timeStamp");
        map.put("userId", userId.asLong());
        map.put("timeStamp", timeStamp.asLong());
        System.out.println("\t解析token ==>" + map.toString());
        return map;
    }
}
